<template>
  <div class="layout-container">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside :width="sidebarWidth" class="sidebar">
        <div class="logo">
          <el-icon v-if="!isCollapse" style="margin-right: 8px;"><School /></el-icon>
          <el-icon v-else><School /></el-icon>
          <span v-if="!isCollapse">考试系统</span>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :unique-opened="false"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <!-- 首页菜单 - 固定显示 -->
          <el-menu-item index="/dashboard">
            <el-icon><HomeFilled /></el-icon>
            <template #title>首页</template>
          </el-menu-item>
          
          <!-- 动态菜单 -->
          <template v-for="menu in userMenus" :key="menu.id">
            <!-- 有子菜单的情况 -->
            <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="String(menu.id)">
              <template #title>
                <el-icon><component :is="menu.icon" /></el-icon>
                <span>{{ menu.name }}</span>
              </template>
              
              <!-- 子菜单项 -->
              <el-menu-item 
                v-for="child in menu.children" 
                :key="child.id" 
                :index="child.path || String(child.id)"
              >
                <el-icon><component :is="child.icon" /></el-icon>
                <template #title>{{ child.name }}</template>
              </el-menu-item>
            </el-sub-menu>
            
            <!-- 没有子菜单的情况 -->
            <el-menu-item v-else :index="menu.path || String(menu.id)">
              <el-icon><component :is="menu.icon" /></el-icon>
              <template #title>{{ menu.name }}</template>
            </el-menu-item>
          </template>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header class="header">
          <div class="header-left">
            <el-button link class="sidebar-toggle" @click="toggleSidebar">
              <el-icon><Fold v-if="!isCollapse" /><Expand v-else /></el-icon>
            </el-button>
          </div>
          
          <div class="header-right">
            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand" class="user-dropdown">
              <span class="user-info">
                <el-avatar v-if="userAvatar" :src="userAvatar" :size="32" />
                <el-avatar v-else :size="32">
                  <el-icon><Avatar /></el-icon>
                </el-avatar>
                <span class="username">{{ userName }}</span>
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人资料
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
                <el-dropdown-item command="settings">
                  <el-icon><Setting /></el-icon>
                  设置
                </el-dropdown-item>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <!-- 新的标签页导航 -->
        <div class="tabs-container">
          <div class="tabs-wrapper">
            <!-- 上一个标签页按钮 -->
            <div class="tabs-nav-btn" @click="gotoPrevTab">
              <el-icon><ArrowLeft /></el-icon>
            </div>
            
            <!-- 标签页滚动区域 -->
            <div class="tabs-scroll-container" ref="tabsScrollContainer">
              <div class="tabs-nav" ref="tabsNav">
                <div 
                  v-for="tab in tabs" 
                  :key="tab.name"
                  :class="['tab-item', { 'is-active': activeTab === tab.name }]"
                  @click="handleTabClick(tab)"
                  @contextmenu="handleTabContextMenu($event, tab)"
                >
                  <span class="tab-title">{{ tab.title }}</span>
                  <el-icon 
                    v-if="tab.closable" 
                    class="tab-close"
                    @click.stop="handleTabRemove(tab.name)"
                  >
                    <Close />
                  </el-icon>
                </div>
              </div>
            </div>
            
            <!-- 下一个标签页按钮 -->
            <div class="tabs-nav-btn" @click="gotoNextTab">
              <el-icon><ArrowRight /></el-icon>
            </div>
            
            <!-- 更多操作按钮 -->
            <el-dropdown @command="handleTabsCommand" class="tabs-more">
              <div class="tabs-more-btn">
                <el-icon><More /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="closeOthers">
                    <el-icon><CircleClose /></el-icon>
                    关闭其他
                  </el-dropdown-item>
                  <el-dropdown-item command="closeAll">
                    <el-icon><Delete /></el-icon>
                    关闭全部
                  </el-dropdown-item>
                  <el-dropdown-item divided command="refresh">
                    <el-icon><Refresh /></el-icon>
                    刷新页面
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <!-- 主要内容 -->
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { permissionApi, type MenuTreeItem } from '@/api/permissions'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const isCollapse = ref(false)
const loading = ref(false)

// 添加一个标志来跟踪路由加载状态
const isRoutesLoading = ref(false)

const currentContextTab = ref()

// 直接使用 store 中的菜单数据
const userMenus = computed(() => authStore.userMenus)

const sidebarWidth = computed(() => isCollapse.value ? '64px' : '200px')

interface TabItem {
  name: string
  title: string
  path: string
  closable?: boolean
  originalPath?: string  // 原始路径，用于显示正确的菜单名称
}

// 标签页相关状态 - 从localStorage恢复
const initTabs = (): TabItem[] => {
  try {
    const savedTabs = localStorage.getItem('tabs')
    if (savedTabs) {
      const parsedTabs = JSON.parse(savedTabs)
      return parsedTabs
    }
  } catch (error) {
    console.error('[initTabs] 恢复标签页数据失败:', error)
  }
  
  // 默认只有首页
  return [{ name: 'dashboard', title: '首页', path: '/dashboard', closable: false }]
}

const tabs = ref<TabItem[]>(initTabs())

// 从localStorage恢复activeTab
const initActiveTab = (): string => {
  try {
    const savedActiveTab = localStorage.getItem('activeTab')
    if (savedActiveTab) {
      return savedActiveTab
    }
  } catch (error) {
    console.error('[initActiveTab] 恢复激活标签页失败:', error)
  }
  return 'dashboard'
}

const activeTab = ref(initActiveTab())

// 保存标签页数据到localStorage
const saveTabsToStorage = () => {
  try {
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    localStorage.setItem('activeTab', activeTab.value)
  } catch (error) {
    console.error('[saveTabsToStorage] 保存标签页数据失败:', error)
  }
}

const activeMenu = computed(() => {
  return route.path
})

const userName = computed(() => {
  return authStore.user?.fullName || authStore.user?.username || '用户'
})

const userAvatar = computed(() => {
  return authStore.user?.avatar || ''
})

// 添加调试函数，打印完整的菜单数据结构
const debugMenuData = () => {  
  // 遍历所有菜单项，打印路径和名称
  const printMenuItems = (menus: MenuTreeItem[], level = 0) => {
    menus.forEach(menu => {
      if (menu.children && menu.children.length > 0) {
        printMenuItems(menu.children, level + 1)
      }
    })
  }
  
  if (userMenus.value.length > 0) {
    printMenuItems(userMenus.value)
  }
}

// 处理菜单点击 - 确保正确获取菜单名称
const handleMenuSelect = async (index: string) => {  
  if (index) {
    const fullPath = index.startsWith('/') ? index : `/${index}`
    
    // 查找菜单信息
    const menuInfo = findMenuByPath(fullPath)
    const tabName = fullPath.replace(/^\//, '') || 'not-found'
    
    // 如果找不到菜单信息，说明菜单数据可能还没加载完成
    if (!menuInfo) {
      // 可以添加一个延迟重试机制
      setTimeout(() => {
        const retryMenuInfo = findMenuByPath(fullPath)
        console.log('[handleMenuSelect] 重试查找菜单:', retryMenuInfo)
      }, 100)
    }
    
    const tabTitle = menuInfo ? menuInfo.name : fullPath.replace(/^\//, '')
    
    // 检查路由是否存在
    const matchedRoute = router.resolve(fullPath)
    if (matchedRoute.name === 'NotFound') {      
      console.log('[handleMenuSelect] 路由不存在:', fullPath)
      addOrActiveTab({
        name: tabName,
        title: tabTitle,
        path: '/404',
        closable: true,
        originalPath: fullPath
      })
      
      router.push('/404')
      return
    }
    
    // 路由存在，尝试跳转
    try {
      addOrActiveTab({
        name: tabName,
        title: tabTitle,
        path: fullPath,
        closable: true
      })
      
      await router.push(fullPath)
    } catch (error) {    
      console.error('[handleMenuSelect] 路由跳转失败:', error)  
      const existingTabIndex = tabs.value.findIndex(t => t.name === tabName)
      if (existingTabIndex !== -1) {
        tabs.value[existingTabIndex] = {
          name: tabName,
          title: tabTitle,
          path: '/404',
          closable: true,
          originalPath: fullPath
        }
      }
      
      router.push('/404')
    }
  }
}

// 修复查找菜单信息的函数 - 支持多种路径格式匹配
const findMenuByPath = (path: string): MenuTreeItem | null => {
  
  if (!userMenus.value || userMenus.value.length === 0) {
    return null
  }
  
  const findInMenus = (menus: MenuTreeItem[]): MenuTreeItem | null => {
    for (const menu of menus) {      
      // 多种路径匹配方式
      if (menu.path === path || 
          menu.path === `/${path}` || 
          `/${menu.path}` === path ||
          menu.path?.replace(/^\//, '') === path.replace(/^\//, '')) {
        return menu
      }
      
      // 递归检查子菜单
      if (menu.children && menu.children.length > 0) {
        const found = findInMenus(menu.children)
        if (found) return found
      }
    }
    return null
  }
  
  const result = findInMenus(userMenus.value)
  return result
}

// 添加或激活标签页 - 添加保存逻辑
const addOrActiveTab = (tab: TabItem) => {
  console.log('[addOrActiveTab] 处理标签页:', tab)
  
  // 如果要添加的是404标签页，但当前路由不是真正的404，则不处理
  if (tab.path === '/404' && (route.path !== '/404' || route.name !== 'NotFound')) {
    return
  }
  
  const existingTabIndex = tabs.value.findIndex(t => t.name === tab.name)
  if (existingTabIndex !== -1) {
    // 标签页已存在，只激活
    activeTab.value = tab.name
  } else {
    // 添加新标签页
    tabs.value.push(tab)
    activeTab.value = tab.name
  }
  
  saveTabsToStorage()
}

// 处理标签页点击 - 修复404页面处理
const handleTabClick = (tab: TabItem) => {
  // 如果点击的是404标签页，检查是否有多个404标签页
  if (tab.path === '/404') {
    // 移除所有多余的404标签页，只保留一个
    const errorTabs = tabs.value.filter(t => t.path === '/404')
    if (errorTabs.length > 1) {
      // 保留第一个，移除其他的
      for (let i = 1; i < errorTabs.length; i++) {
        const index = tabs.value.findIndex(t => t === errorTabs[i])
        if (index !== -1) {
          tabs.value.splice(index, 1)
        }
      }
      saveTabsToStorage()
    }
  }
  
  activeTab.value = tab.name
  saveTabsToStorage()
  
  // 如果是404页面且有原始路径，尝试跳转到原始路径
  if (tab.path === '/404' && tab.originalPath) {
    const matchedRoute = router.resolve(tab.originalPath)
    if (matchedRoute.name !== 'NotFound') {
      router.push(tab.originalPath)
      return
    }
  }
  
  router.push(tab.path)
}

// 处理标签页关闭 - 添加保存逻辑
const handleTabRemove = (tabName: string) => {
  const tabIndex = tabs.value.findIndex(t => t.name === tabName)
  if (tabIndex === -1) return
  
  const tab = tabs.value[tabIndex]
  if (!tab.closable) return
  
  tabs.value.splice(tabIndex, 1)
  
  // 如果关闭的是当前激活的标签页，需要切换到其他标签页
  if (activeTab.value === tabName) {
    const newActiveTab = tabs.value[Math.max(0, tabIndex - 1)]
    activeTab.value = newActiveTab.name
    router.push(newActiveTab.path)
  }
  
  // 保存到localStorage
  saveTabsToStorage()
}

// 处理标签页右键菜单
const handleTabContextMenu = (event: MouseEvent, tab?: TabItem) => {
  event.preventDefault()
  if (tab) {
    currentContextTab.value = tab
  }
  // 这里可以显示自定义的右键菜单
}

// 添加一个标志来跟踪是否正在处理路由守卫的重定向
const isRouterRedirecting = ref(false)

// 监听路由变化 - 完全避免临时404标签页
watch(() => route.path, (newPath, oldPath) => {  
  console.log('[handleTabClick] 处理路由变化:',route,route.name, newPath, oldPath)
  // 如果是404页面
  if (newPath === '/404') {
    // 检查是否是路由守卫的临时重定向
    if (route.name !== 'NotFound') {
      isRouterRedirecting.value = true
      return
    }
    
    // 如果是从正常页面刷新导致的临时404，也忽略
    if (oldPath && oldPath !== '/404' && oldPath !== '/login') {
      isRouterRedirecting.value = true
      return
    }
    
    // 只有真正的404页面才处理
    const existingTab = tabs.value.find(t => t.path === '/404')
    if (!existingTab) {
      console.log('[handleTabClick] 处理404页面:',tabs, newPath,route.name)
      addOrActiveTab({
        name: '404',
        title: '页面未找到',
        path: '/404',
        closable: true
      })
    } else {
      activeTab.value = existingTab.name
      saveTabsToStorage()
    }
    return
  }
  
  // 如果从404跳转回正常页面，重置重定向标志
  if (oldPath === '/404' && isRouterRedirecting.value) {
    isRouterRedirecting.value = false
  }
  
  // 处理正常页面
  const tabName = newPath.replace(/^\//, '') || 'dashboard'
  
  // 检查标签页是否存在
  const existingTab = tabs.value.find(t => t.name === tabName)
  if (existingTab) {
    activeTab.value = tabName
    saveTabsToStorage()
    return
  }
  
  // 创建新标签页
  let tabTitle: string
  
  if (newPath === '/dashboard') {
    tabTitle = '首页'
  } else {
    const menuInfo = findMenuByPath(newPath)
    if (menuInfo && menuInfo.name) {
      tabTitle = menuInfo.name
    } else if (route.meta?.title) {
      tabTitle = route.meta.title as string
    } else {
      tabTitle = newPath.replace(/^\//, '')
    }
  }
  
  addOrActiveTab({
    name: tabName,
    title: tabTitle,
    path: newPath,
    closable: newPath !== '/dashboard'
  })
}, { immediate: true })

// 在菜单数据变化时，更新现有标签页的标题
watch(() => userMenus.value, (newMenus) => {
  if (newMenus && newMenus.length > 0) {
    
    // 更新现有标签页的标题
    tabs.value.forEach(tab => {
      if (tab.name !== 'dashboard' && tab.path !== '/404') {
        const menuInfo = findMenuByPath(tab.path)
        if (menuInfo && menuInfo.name && tab.title !== menuInfo.name) {
          tab.title = menuInfo.name
        }
      }
    })
    
    saveTabsToStorage()
  }
}, { deep: true })

// 清理标签页数据的函数（登出时调用）
const clearTabsStorage = () => {
  localStorage.removeItem('tabs')
  localStorage.removeItem('activeTab')
  tabs.value = [{ name: 'dashboard', title: '首页', path: '/dashboard', closable: false }]
  activeTab.value = 'dashboard'
}

// 获取用户菜单 - 添加路由加载状态控制
const fetchUserMenus = async () => {  
  if (loading.value) return
  
  // 检查缓存
  authStore.getMenus()
  if (authStore.userMenus.length > 0) {
    debugMenuData()
    addRoutesFromMenus(authStore.userMenus)
    return
  }
  
  loading.value = true
  isRoutesLoading.value = true // 设置路由加载状态
  
  try {
    if (!authStore.token || !authStore.user) {
      return
    }
    
    const response = await permissionApi.getMenuTree()
    
    if (response.data && Array.isArray(response.data)) {
      authStore.setMenus(response.data)
      debugMenuData()
      addRoutesFromMenus(response.data)
    }
  } catch (error) {
    console.error('[fetchUserMenus] 获取菜单失败:', error)
  } finally {
    loading.value = false
    // 延迟重置路由加载状态，确保路由完全加载完成
    setTimeout(() => {
      isRoutesLoading.value = false
    }, 100)
  }
}

// 从菜单数据添加路由的辅助函数
const addRoutesFromMenus = (menus: MenuTreeItem[]) => {  
  const processMenu = (menu: MenuTreeItem, parentPath = '') => {    
    if (menu.path && menu.component) {
      const fullPath = menu.path.startsWith('/') ? menu.path : `/${menu.path}`      
      try {
        // 动态导入组件
        const component = () => import(/* @vite-ignore */ `../views/${menu.component}`)
        
        router.addRoute('MainLayout', {
          path: fullPath,
          name: menu.name || fullPath.replace(/\//g, '-'),
          component,
          meta: {
            title: menu.name,
            breadcrumb: generateBreadcrumb(menu),
            requiresAuth: true
          }
        })
      } catch (error) {        
        // 如果组件不存在，添加到默认页面
        router.addRoute('MainLayout', {
          path: fullPath,
          name: menu.name || fullPath.replace(/\//g, '-'),
          component: () => import('@/views/common/ComponentNotFoundView.vue'),
          meta: {
            title: menu.name,
            breadcrumb: generateBreadcrumb(menu),
            requiresAuth: true
          }
        })
      }
    }
    
    // 递归处理子菜单
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => processMenu(child, menu.path))
    }
  }
  
  menus.forEach(menu => processMenu(menu))
  console.log('[MainLayout] 动态路由添加完成')
}

// 生成面包屑 - 支持多级菜单
const generateBreadcrumb = (menu: MenuTreeItem, parentMenus: MenuTreeItem[] = []): string[] => {
  const breadcrumb = ['首页']
  
  // 添加父级菜单
  parentMenus.forEach(parent => {
    breadcrumb.push(parent.name)
  })
  
  // 添加当前菜单
  breadcrumb.push(menu.name)
  
  return breadcrumb
}

const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

const handleCommand = async (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 清理标签页数据
        clearTabsStorage()
        
        await authStore.logout()
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        console.log('取消退出')
      }
      break
  }
}

// 监听认证状态变化 - 确保菜单及时加载
watch(() => [authStore.user, authStore.token], (newValues) => {
  const [newUser, newToken] = newValues || []
  
  if (newUser && newToken) {
    console.log('[MainLayout] 用户已认证，加载菜单')
    nextTick(() => {
      fetchUserMenus()
    })
  } else {
    console.log('[MainLayout] 用户未认证，清空菜单')
  }
}, { immediate: true })

onMounted(() => {  
  // 清理所有错误的404标签页
  const before = tabs.value.length
  tabs.value = tabs.value.filter(t => {
    if (t.path === '/404') {
      // 只有当前确实在404页面且是真正的NotFound时才保留
      return route.path === '/404' && route.name === 'NotFound'
    }
    return true
  })
  
  if (tabs.value.length !== before) {
    console.log('[MainLayout] 清理了错误的404标签页')
    saveTabsToStorage()
  }
  
  // 加载菜单
  if (authStore.user && authStore.token) {
    fetchUserMenus()
  }
})

// 标签页滚动相关
const tabsScrollContainer = ref<HTMLElement>()
const tabsNav = ref<HTMLElement>()

// 检查是否需要显示滚动按钮
const showScrollButtons = ref(false)

const checkScrollButtons = () => {
  if (!tabsScrollContainer.value || !tabsNav.value) return
  
  const containerWidth = tabsScrollContainer.value.clientWidth
  const navWidth = tabsNav.value.scrollWidth
  
  showScrollButtons.value = navWidth > containerWidth
}

// 监听标签页变化，检查是否需要滚动按钮
watch(() => tabs.value.length, () => {
  nextTick(() => {
    checkScrollButtons()
  })
})

onMounted(() => {
  nextTick(() => {
    checkScrollButtons()
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', checkScrollButtons)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkScrollButtons)
})

// 处理标签页操作命令
const handleTabsCommand = (command: string) => {
  switch (command) {
    case 'closeOthers':
      tabs.value = tabs.value.filter(tab => 
        !tab.closable || tab.name === activeTab.value
      )
      saveTabsToStorage()
      break
    case 'closeAll':
      tabs.value = tabs.value.filter(tab => !tab.closable)
      if (activeTab.value !== 'dashboard') {
        activeTab.value = 'dashboard'
        router.push('/dashboard')
      }
      saveTabsToStorage()
      break
    case 'refresh':
      window.location.reload()
      break
  }
}

// 切换到上一个标签页
const gotoPrevTab = () => {
  const currentIndex = tabs.value.findIndex(tab => tab.name === activeTab.value)
  if (currentIndex > 0) {
    const prevTab = tabs.value[currentIndex - 1]
    activeTab.value = prevTab.name
    router.push(prevTab.path)
    saveTabsToStorage()
    
    // 滚动到可见区域
    scrollToActiveTab()
  }
}

// 切换到下一个标签页
const gotoNextTab = () => {
  const currentIndex = tabs.value.findIndex(tab => tab.name === activeTab.value)
  if (currentIndex < tabs.value.length - 1) {
    const nextTab = tabs.value[currentIndex + 1]
    activeTab.value = nextTab.name
    router.push(nextTab.path)
    saveTabsToStorage()
    
    // 滚动到可见区域
    scrollToActiveTab()
  }
}

// 滚动到激活的标签页
const scrollToActiveTab = () => {
  if (!tabsScrollContainer.value || !tabsNav.value) return
  
  const activeTabElement = tabsNav.value.querySelector('.tab-item.is-active') as HTMLElement
  if (!activeTabElement) return
  
  const containerRect = tabsScrollContainer.value.getBoundingClientRect()
  const tabRect = activeTabElement.getBoundingClientRect()
  
  // 如果标签页不在可见区域内，滚动到可见位置
  if (tabRect.left < containerRect.left || tabRect.right > containerRect.right) {
    const scrollLeft = activeTabElement.offsetLeft - (tabsScrollContainer.value.clientWidth / 2) + (activeTabElement.clientWidth / 2)
    tabsScrollContainer.value.scrollTo({
      left: Math.max(0, scrollLeft),
      behavior: 'smooth'
    })
  }
}
</script>

<style scoped>
/* 去掉所有焦点框 */
* {
  outline: none !important;
}

*:focus {
  outline: none !important;
  box-shadow: none !important;
}

.layout-container {
  height: 100vh;
  overflow: hidden;
}

.sidebar {
  background-color: #001529;
  transition: width 0.3s;
  overflow: hidden;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1890ff;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #1f2937;
  background-color: #001529;
}

.sidebar-menu {
  border: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
  background-color: #001529;
}

/* 确保菜单样式正确 */
.sidebar-menu {
  border: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
  background-color: #001529;
}

/* 菜单项样式 */
.sidebar-menu .el-menu-item {
  color: #ffffff !important;
  background-color: #001529 !important;
}

.sidebar-menu .el-menu-item.is-active {
  color: #409eff !important;
  background-color: #0c2135 !important;
}

.sidebar-menu .el-sub-menu__title {
  color: #ffffff !important;
  background-color: #001529 !important;
}

/* 确保菜单可见 */
.el-menu {
  border-right: none !important;
}

.el-menu--collapse {
  width: 64px;
}

/* 子菜单样式 */
.sidebar-menu .el-sub-menu__title {
  color: #ffffff !important;
  background-color: #001529 !important;
}

.sidebar-menu .el-sub-menu__title:hover {
  background-color: #1f2937 !important;
  color: #1890ff !important;
}

/* 使用深度选择器确保样式生效 */
:deep(.sidebar-menu .el-sub-menu .el-menu-item) {
  background-color: #1a2332 !important;
  color: #ffffff !important;
  border-left: 3px solid transparent !important;
}

:deep(.sidebar-menu .el-sub-menu .el-menu-item:hover) {
  background-color: #2d3748 !important;
  color: #409eff !important;
  border-left: 3px solid #409eff !important;
}

:deep(.sidebar-menu .el-sub-menu .el-menu-item.is-active) {
  background-color: #409eff !important;
  color: #ffffff !important;
  border-left: 3px solid #409eff !important;
}

/* 子菜单容器背景 */
:deep(.sidebar-menu .el-menu--inline) {
  background-color: #0f1419 !important;
}

/* 确保子菜单标题样式 */
:deep(.sidebar-menu .el-sub-menu__title) {
  color: #ffffff !important;
  background-color: #001529 !important;
}

:deep(.sidebar-menu .el-sub-menu__title:hover) {
  background-color: #1f2937 !important;
  color: #409eff !important;
}

/* 展开的子菜单标题 */
:deep(.sidebar-menu .el-sub-menu.is-opened .el-sub-menu__title) {
  background-color: #001529 !important;
  color: #409eff !important;
}

.user-dropdown:hover {
  background-color: #f5f5f5;
}

.username {
  font-size: 14px;
  color: #606266;
}

.el-main {
  background: #f0f2f5;
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 60px);
}

.header {
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-right {
  display: flex;
  align-items: center;
}

.sidebar-toggle {
  font-size: 18px;
  color: #666;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.username {
  font-size: 14px;
  color: #606266;
}

.tabs-container {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  height: 40px;
  display: flex;
  align-items: center;
}

.tabs-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
}

.tabs-nav-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #909399;
  transition: all 0.2s;
  margin: 0 4px;
  border-radius: 4px;
  outline: none !important;
  border: none !important;
}

.tabs-nav-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.tabs-nav-btn:focus {
  outline: none !important;
  box-shadow: none !important;
}

.tabs-scroll-container {
  flex: 1;
  overflow: hidden;
  height: 100%;
}

.tabs-nav {
  display: flex;
  align-items: center;
  height: 100%;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
  padding: 0 8px;
}

.tabs-nav::-webkit-scrollbar {
  display: none;
}

.tab-item {
  display: flex;
  align-items: center;
  padding: 0 16px;
  height: 32px;
  background: #f5f7fa;
  border: none !important;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  color: #606266;
  transition: all 0.2s;
  margin-right: 6px;
  white-space: nowrap;
  flex-shrink: 0;
  position: relative;
  outline: none !important;
}

.tab-item:focus {
  outline: none !important;
  box-shadow: none !important;
}

.tab-item:hover {
  background: #ecf5ff;
  color: #409eff;
}

.tab-item.is-active {
  background: #409eff;
  color: #fff;
  font-weight: 500;
}

.tab-item.is-active:hover {
  background: #337ecc;
}

.tab-title {
  margin-right: 6px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tab-close {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  opacity: 0.7;
}

.tab-close:hover {
  background: rgba(255, 255, 255, 0.2);
  opacity: 1;
}

.tab-item.is-active .tab-close:hover {
  background: rgba(255, 255, 255, 0.3);
}

.tabs-more {
  margin-left: 8px;
  margin-right: 12px;
}

.tabs-more-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #909399;
  transition: all 0.2s;
  border-radius: 4px;
  outline: none !important;
  border: none !important;
}

.tabs-more-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.tabs-more-btn:focus {
  outline: none !important;
  box-shadow: none !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .tabs-nav-btn {
    display: none;
  }
  
  .tab-item {
    padding: 0 12px;
    margin-right: 4px;
  }
  
  .tab-title {
    max-width: 80px;
  }
}
</style>
